//
//  Binding.swift
//  HealthMonitoring
//
//  Created by 珠海正杰 on 2018/6/11.
//  Copyright © 2018年 YTYanK. All rights reserved.
//

import UIKit
import RKDropdownAlert
class Binding: HMViewController, UITextFieldDelegate {
    // MARK: - 变量
    
    
    // 遮罩view
    var _maskView: UIView?
    /// 是否是更改绑定界面-从设置进来
    var isChangeUI: Bool = false
    var oldCode: Int = 0    // 旧手机获取到的验证码
    
    // MARK: - 常量
    let bgImg = UIImageView()
    let photoField = UITextField()
    let smsField = UITextField()
    let smsButton = UIButton()
    let nextStep = UIButton()
    
    // 线条
    let line = UIView()
    let line1 = UIView()
    let lineVertical = UIView() //竖线
    
    // MARK: - 周期
    override func viewDidLoad() {
        super.viewDidLoad()
        keyBordNotification(this: self, aShow: #selector(keyBoardWillShow(_:)), aHide: #selector(keyBoardWillHide(_:)))
    }
    
    deinit {
        //移除通知
        NotificationCenter.default.removeObserver(self)
    }
    
    // MARK: - 配置view
    override func setupView() {
        if isChangeUI  {
          self.title = "更改手机绑定"
        }else {
          self.title = "绑定界面"
        }
        
        view.backgroundColor = UIColor.white
         _maskView = UIView.createMaskView(this: self, action: #selector(onMark))
        
        view.addSubview(bgImg)
        view.addSubview(photoField)
        view.addSubview(line)
        view.addSubview(smsField)
        view.addSubview(lineVertical)
        view.addSubview(smsButton)
        view.addSubview(line1)
        view.addSubview(nextStep)
        
        bgImg.image = UIImage.init(named: "bg.png")
        bgImg.centerXYAlign(view: view)
        bgImg.height(view: view)
        bgImg.width(view: view)
        
        photoField.topAlign(view: view, predicate: "30")
        photoField.leadingAlign(view: view, predicate: "60")
        photoField.trailingAlign(view: view, predicate: "-60")
        photoField.heightConstrain(predicate: "44")
        photoField.tag = 102
        photoField.placeholder = "请输入已绑定手机号"
        photoField.delegate = self
        photoField.text = ""
        photoField.setValue(UIFont.systemFont(ofSize: 15), forKeyPath: "_placeholderLabel.font")
        photoField.setValue(UIColor.gray, forKeyPath: "_placeholderLabel.textColor")


        line.topVertically(view: photoField, predicate: "0")
        line.leadingAlign(view: view, predicate: "60")
        line.trailingAlign(view: view, predicate: "-60")
        line.backgroundColor = UIColor.gray
        line.heightConstrain(predicate: "2")

        if isChangeUI == true {
            smsField.topVertically(view: line, predicate: "10")
            smsField.leadingAlign(view: view, predicate: "60")
            smsField.trailingAlign(view: view, predicate: "-60")
            smsField.heightConstrain(predicate: "44")
            smsField.tag = 101
            smsField.placeholder = "验证码"
            smsField.delegate = self
            smsField.setValue(UIFont.systemFont(ofSize: 15), forKeyPath: "_placeholderLabel.font")
            smsField.setValue(UIColor.gray, forKeyPath: "_placeholderLabel.textColor")
            smsField.keyboardType = UIKeyboardType.numberPad
            smsField.returnKeyType = UIReturnKeyType.done
            
            smsButton.topVertically(view: line, predicate: "10")
            smsButton.trailingAlign(view: smsField, predicate: "0")
            smsButton.heightConstrain(predicate: "44")
            smsButton.widthConstrain(predicate: "100")
            smsButton.titleLabel?.font = UIFont.systemFont(ofSize: 15)
            smsButton.addTarget(self, action: #selector(getCodeVerifying(sender:)), for: .touchUpInside)
            smsButton.setTitleColor(configure.shareConfigure.HMColor1, for: .normal)
            smsButton.setTitle("获取验证码", for: .normal)
            
            
            
            lineVertical.topVertically(view: line, predicate: "10")
            lineVertical.leadingAlign(view: smsButton, predicate: "0")
            lineVertical.heightConstrain(predicate: "42")
            lineVertical.backgroundColor = UIColor.gray
            lineVertical.widthConstrain(predicate: "2")
            
            
            line1.topVertically(view: smsField, predicate: "0")
            line1.leadingAlign(view: view, predicate: "60")
            line1.trailingAlign(view: view, predicate: "-60")
            line1.backgroundColor = UIColor.gray
            line1.heightConstrain(predicate: "2")
        }else {
            
        }
        
        
        if isChangeUI == true  {
          nextStep.topVertically(view: line1, predicate: "65")
        }else {
          nextStep.topVertically(view: line, predicate: "65")
        }
        nextStep.leadingAlign(view: view, predicate: "60")
        nextStep.trailingAlign(view: view, predicate: "-60")
        nextStep.backgroundColor =   configure.shareConfigure.HMColor3
        nextStep.isEnabled = false
        nextStep.heightConstrain(predicate: "44")
        nextStep.setTitle("下一步", for: .normal)
        nextStep.setTitleColor(UIColor.white, for: .normal)
        nextStep.addTarget(self, action: #selector(nextStepClick), for: .touchUpInside)
        nextStep.layer.cornerRadius = 20
        self.setButtonSytle()
        
    }
    
    /**
     获取验证码
     */
    @objc func getCodeVerifying(sender: UIButton){
          let photoNum = photoField.text! as String
        if String.isTelNumber(num: photoNum) == true {
            sender.countdownButton(second: 60, title: "获取验证码")
            
            NetRequestTool.shareInstance.met = .get
            NetRequestTool.request(url: "sms-code/rebind-old/send", parameters: ["phone" : photoNum], success: { (json) in
                self.showToast(message: json["msg"].stringValue)
            }, fail: { (error, msg) in
                 RKDropdownAlert.title("温馨提醒!", message: msg)
            }) { }
            
        }
    
    }
    
    
    /**
     nextStepClick
     */
    @objc func nextStepClick() {
        
            let _str: String = photoField.text! as String
            
            if (String.isTelNumber(num: _str) == true) {
                // 这个是获取问题列表
                
                if isChangeUI {
                   let _signUp = SignUp()
                    _signUp.oldPhone = _str
                    _signUp.isChangeUI = self.isChangeUI
                    _signUp.oldCode = self.smsField.text!
                    self.pushViewController(_signUp)
                    
                }else {
                
                        NetRequestTool.request(url: "security-config", parameters: [:], success: { (json) in
                            let _bindingChange = BindingChange()
                            _bindingChange._signStr = "更改绑定"
                           
                            _bindingChange.oldPhone = self.photoField.text
                            _bindingChange.pickerAry = json["data"].arrayObject
                            self.pushViewController(_bindingChange)
                            
                        }, fail: { (error, msg) in
                            print("------------ \(error)")
                        }) {
                             //
                        }
               }
                
            }else {
                RKDropdownAlert.title("温馨提醒！", message: "手机格式错误，请重新输入")
            }
    
    }
    
    /**
     键盘监控
     */
    @objc func keyBoardWillShow(_ notification: Notification){
        self.view.window?.addSubview(_maskView!)
       // print("------->>keyBoardWillShow")
    }
    
    @objc func keyBoardWillHide(_ notification: Notification){
       // print("------->>keyBoardWillHide")
        self.setButtonSytle()
    }
    
    // UITapGestureRecognizer
    @objc func onMark(send: UITapGestureRecognizer) {
        _maskView?.removeFromSuperview()
        if isChangeUI == true  {
           self.smsField.resignFirstResponder()//结束编辑状态
        }
        self.photoField.resignFirstResponder()//结束编辑状态
    }
    // 设
    
    // 设置按钮表现效果
    func setButtonSytle()  {
        //判断是否开启按钮
       
            if (self.photoField.text!.count > 0) {
                 if isChangeUI == true {
                    if  self.smsField.text!.count > 0 {
                       openButtonRecognition(setStyleBtn: self.nextStep, isOpen: true)
                    }else {
                       openButtonRecognition(setStyleBtn: self.nextStep, isOpen: false)
                    }
                 }else {
                   openButtonRecognition(setStyleBtn: self.nextStep, isOpen: true)
                }
            }else {
                openButtonRecognition(setStyleBtn: self.nextStep, isOpen: false)
            }
    
        
       
    }
    
    
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let text = textField.text!
        let len = text.count + string.count - range.length
        if textField.tag == 101 {
            return (len <= 6)
        }else {
            return (len <= 11)
        }

    }
}
